/*
 * Copyright 2021 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.thoughtworks.go.addon.businesscontinuity;

import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.io.FileUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;

import java.io.File;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static java.lang.System.getProperty;

@org.springframework.context.annotation.Configuration
public class Configuration {

    @Bean
    public CloseableHttpClient httpClient(SystemEnvironment systemEnvironment) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        File trustFile = new File(systemEnvironment.getConfigDir(), "standby-trust.jks");
        File certificateFile = new File(systemEnvironment.getConfigDir(), "standby-cert.jks");
        FileUtils.deleteQuietly(trustFile);
        FileUtils.deleteQuietly(certificateFile);

        HttpClientBuilder builder = HttpClients.custom();
        builder.useSystemProperties();
        builder
                .setDefaultSocketConfig(SocketConfig.custom()
                        .setTcpNoDelay(true)
                        .setSoKeepAlive(true)
                        .setSoTimeout(primaryServerTimeout())
                        .build()
                )
                .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
        builder.setConnectionTimeToLive(primaryServerTimeout(), TimeUnit.MILLISECONDS);

        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.loadTrustMaterial(null, TrustAllStrategy.INSTANCE);

        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
        builder.setSSLSocketFactory(sslConnectionSocketFactory);

        return builder.build();
    }

    @Bean
    public ScheduledExecutorService scheduledExecutorService() {
        return Executors.newSingleThreadScheduledExecutor();
    }

    private int primaryServerTimeout() {
        try {
            return Integer.parseInt(getProperty("primary.server.connection.timeout"));
        } catch (Exception e) {
            return 30 * 1000;
        }
    }
}
